//
//  ImageListController.m
//  Doctor
//
//  Created by kane on 14-11-4.
//  Copyright (c) 2014年 kane. All rights reserved.
//

#import "ImageListController.h"
#import "AppDelegate.h"

@interface ImageListController ()<UIScrollViewDelegate,UIActionSheetDelegate>
{
    __weak IBOutlet UILabel *titleLbl;
    __weak IBOutlet UIScrollView *fileScroll;
    __weak IBOutlet UIView *descView;
    __weak IBOutlet UITextView *descTV;
}

@end

@implementation ImageListController
@synthesize imageList,currentIndex,currentImgView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initUI];
    [self loadCurrentPage];
    // Do any additional setup after loading the view from its nib.
}

- (void)initUI
{
    NSInteger sum = [imageList count];
    for (int i = 0;i < sum; i++) {
        id file = [imageList objectAtIndex:i];
        UIScrollView *itemScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(fileScroll.frame.size.width*i, 0, fileScroll.frame.size.width, fileScroll.frame.size.height)];
        itemScroll.backgroundColor = [UIColor clearColor];
        itemScroll.contentSize = CGSizeMake(fileScroll.frame.size.width, fileScroll.frame.size.height);
        itemScroll.showsHorizontalScrollIndicator = NO;
        itemScroll.showsVerticalScrollIndicator = NO;
        itemScroll.delegate = self;
        itemScroll.minimumZoomScale = 1.0;
        itemScroll.maximumZoomScale = 3.0;
        itemScroll.tag = i+1;
        [itemScroll setZoomScale:1.0];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, fileScroll.frame.size.width, fileScroll.frame.size.height)];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        if ([file isKindOfClass:[NSDictionary class]]) {
            NSDictionary *info = (NSDictionary *)file;
            [imageView setImageWithURL:[NSURL URLWithString:info[@"attach"]]];
        }else if ([file isKindOfClass:[UIImage class]]){
            imageView.image = (UIImage *)file;
        }
        else if ([file isKindOfClass:[UIImageView class]])
        {
            UIImageView *temImage = (UIImageView *)file;
            imageView.image = temImage.image;
        }
        imageView.tag = 2000 + i;
        [itemScroll addSubview:imageView];
        [fileScroll addSubview:itemScroll];
    }
    fileScroll.contentSize = CGSizeMake(sum * fileScroll.frame.size.width, fileScroll.frame.size.height);
    if (self.imageDesc && self.imageDesc.length > 0) {
        descView.hidden = NO;
        descTV.textColor = [UIColor whiteColor];
        descTV.text = self.imageDesc;
    }
    
}

- (void)loadCurrentPage
{
    titleLbl.text = [NSString stringWithFormat:@"%ld/%ld",currentIndex + 1,[imageList count]];
    [fileScroll setContentOffset:CGPointMake(currentIndex * fileScroll.frame.size.width, 0) animated:NO];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView != fileScroll) {
        [scrollView setZoomScale:1.0 animated:YES];
    }
    currentIndex = fileScroll.contentOffset.x / fileScroll.frame.size.width;
    titleLbl.text = [NSString stringWithFormat:@"%ld/%ld",currentIndex + 1,[imageList count]];
}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    for (UIView *v in scrollView.subviews){
        return v;
    }
    return nil;
}


#pragma mark - Utility methods

-(CGRect)zoomRectForScale:(float)scale inView:(UIScrollView*)scrollView withCenter:(CGPoint)center {
    
    CGRect zoomRect;
    
    zoomRect.size.height = [scrollView frame].size.height / scale;
    zoomRect.size.width  = [scrollView frame].size.width  / scale;
    
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}

-(CGRect)resizeImageSize:(CGRect)rect{
    //    NSLog(@"x:%f y:%f width:%f height:%f ", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
    CGRect newRect;
    
    CGSize newSize;
    CGPoint newOri;
    
    CGSize oldSize = rect.size;
    if (oldSize.width>=320.0 || oldSize.height>=460.0){
        float scale = (oldSize.width/320.0>oldSize.height/460.0?oldSize.width/320.0:oldSize.height/460.0);
        newSize.width = oldSize.width/scale;
        newSize.height = oldSize.height/scale;
    }
    else {
        newSize = oldSize;
    }
    newOri.x = (320.0-newSize.width)/2.0;
    newOri.y = (460.0-newSize.height)/2.0;
    
    newRect.size = newSize;
    newRect.origin = newOri;
    
    return newRect;
}

#pragma mark - UIButton Events

- (IBAction)backBtnPressed:(id)sender {
   if(![self.navigationController popViewControllerAnimated:YES])
   [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)rightBtnPressed:(id)sender
{
    UIActionSheet *actionSheet  = [[UIActionSheet alloc] initWithTitle:nil
                                                              delegate:self
                                                     cancelButtonTitle:@"取消"
                                                destructiveButtonTitle:nil
                                                     otherButtonTitles:@"发送给朋友",@"保存到本地", nil];
    [actionSheet showInView:[UIApplication sharedApplication].keyWindow];
}

- (IBAction)longPressed:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        [self rightBtnPressed:nil];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
//    if (buttonIndex == 0){
//        if (![UserEntity sharedUser].loginSuccess) {
//            [[AppDelegate appDelegate] showLoginController];
//            return;
//        }
//        UIView *subView = [[fileScroll viewWithTag:currentIndex + 1] viewWithTag:CellOffset + currentIndex];
//        if ([subView isKindOfClass:[UIImageView class]]) {
//            UIImageView *imageView = (UIImageView *)subView;
//            FriendListController *friendsVC = [[FriendListController alloc] init];
//            friendsVC.ShareType = FriendShareTypeImage;
//            friendsVC.ShareImage = imageView.image;
//            [self.navigationController pushViewController:friendsVC animated:YES];
//        }
//    }else if (buttonIndex == 1){
//       UIView *subView = [[fileScroll viewWithTag:currentIndex + 1] viewWithTag:CellOffset + currentIndex];
//        if ([subView isKindOfClass:[UIImageView class]]) {
//            UIImageView *imageView = (UIImageView *)subView;
//            UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//
//        }
//    }
}

// 指定回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

@end
